#!/usr/bin/env python

"""
person.py - A script to create and manipulate a collection of persons

Typical Usage

Start the server by
 % python samples/person.py server localhost:8888

Client runs at python console
>>> import restpy
>>> ps = restpy.reference('localhost:8888', '/persons/')
>>> ps.get()
...
>>> p = ps.create(567)
>>> ps.get()
...
>>> p.get()
>>> p.update(name='Alice')
>>> p.create(greeting='Hello')
...

or another client command line
 % python samples/person.py client localhost:8888

Copyright: Zeng Ke, superisaac.ke@gmail.com
"""

import sys, os
sys.path.insert(0, '.')

from restpy import * 

class Persons(RestObj):
    def __init__(self, url):
        RestObj.__init__(self, url)
        self.children = {}

    def get(self):
        return self.children.values()
    
    def create(self, id):
        robj = Person(id)
        Node.current().create(robj)

        self.children[id] = robj.reference()
        return robj.reference()

class Person(RestObj):
    def __init__(self, id):
        RestObj.__init__(self, '/persons/%s' % id)
        self.id = id
        self.name = 'NoName'
    def update(self, **kwargs):
        if 'name' in kwargs:
            self.name = kwargs['name']

    def get(self):
        return 'u[%s]' % self.name

    def create(self, **kwargs):
        if 'greeting' in kwargs:
            return '%s: %s, Thank you!' % (self.name, kwargs['greeting'])

    def delete(self):
        us = Node.current().get('/persons/')
        del us.children[self.id]
        Node.current().delete(self)


def test():
    us = Persons('/persons/')
    us.create(10001)
    us.create(10002)
    for u in us.get():
        print u.get()

def test_server(args):
    us = Persons('/persons/')
    Node.run(args[0], us)

def test_client(args):
    us = RestRef(args[0], '/persons/')
    u = us.create(9)
    print u.get()
    #print u.delete()
    for u in us.get():
        print '--', u.get()

if __name__ == '__main__':
    if sys.argv[1] == 'server':
        test_server(sys.argv[2:])
    elif sys.argv[1] == 'client':
        test_client(sys.argv[2:])
    else:
        test()
        
